package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.common.utils.UtilFuns;
import com.itheima.domain.system.Role;
import com.itheima.service.system.IRoleService;
import com.itheima.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/system/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    @RequestMapping(value = "/list",name = "分页查询角色数据列表")
    public String list(@RequestParam(defaultValue = "1") int page) {

        int size = 5;



        PageInfo pageInfo = roleService.findAll(super.getCurrentUserCompanyId(), page, size);

        request.setAttribute("page", pageInfo);

        return "system/role/role-list";
    }

    @RequestMapping(value = "/toAdd",name = "前往新建角色页面")
    public String toAdd() {

        return "system/role/role-add";
    }

    @RequestMapping(value = "/toUpdate",name = "前往修改角色页面")
    public String toUpdate(String id) {

        Role role = roleService.findById(id);

        request.setAttribute("role", role);

        return "system/role/role-update";
    }

    @RequestMapping(value = "/edit",name = "保存或者更新角色")
    public String edit(Role role) {

        role.setCompanyId(super.getCurrentUserCompanyId());
        role.setCompanyName(super.getCurrenUserCompanyName());

        if (UtilFuns.isEmpty(role.getId())) {
            //保存

            roleService.save(role);
        } else {
            //更新

            roleService.update(role);
        }

        return "redirect:/system/role/list.do";
    }

    @RequestMapping(value = "/roleModule",name = "前往角色权限页面")
    public String roleModule(@RequestParam("roleid") String id) {

        Role role = roleService.findById(id);

        request.setAttribute("role", role);

        return "system/role/role-module";
    }

    @RequestMapping(value = "/initModuleData",name = "获取角色权限数据")
    public @ResponseBody List<Map> initModuleData(String id) {

        List<Map> list = roleService.findRoleModule(id);

        return list;
    }

    @RequestMapping(value = "/updateRoleModule",name = "更新角色模块权限信息")
    public String updateRoleModule(@RequestParam("roleid") String id, String moduleIds) {

        roleService.updateRoleModule(id, moduleIds);

        return "redirect:/system/role/list.do";

    }

}